var $, layer, form, table, laydate, util, laydate, wherestr = {}, moduleUrl;
var scroll = {X: '', Y: ''};
var pagenum = 1
layui.use(['table', 'form', 'layer', 'jquery', 'laydate', 'element'], function () {
    $ = layui.$, layer = layui.layer, form = layui.form, table = layui.table, laydate = layui.laydate, element = layui.element;
    serachRender();//查询条件初始渲染集合
    sessionStorage.setItem(moduleTable + 'checkdata', '')
    var isbtn = true
    $.tablelist.init({
        elem: '#dhtable',
        url: tableUrl,
        where: getWherestr(),
        totalRow: gridColumns.totalRow,
        cols: [gridColumns.gridBody],
        toolbar: '#toolbar',
        defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
        // ,height:moduleTable!='TCG_PURCHASEPLAN'?'full-46':''
        ,
        height: ['TP_FBALOGISTICSPAYMENT','TP_FBALOGISTICSRECONCILE','TP_FBABOX', 'TP_FBAPLANORDER', 'TCG_PURCHASEPLAN', 'TCG_PURCHASEPLANCANCEL', 'TCG_PAYMENT', 'TCG_PURCHASEORDER'].includes(moduleTable) ? '' : 'full-46'
        ,
        parseData: function (res) { //res 即为原始返回的数据
            if (['TP_FBALOGISTICSPAYMENT','TP_FBALOGISTICSRECONCILE','TP_FBABOX', 'TP_FBAPLANORDER', 'TCG_PURCHASEPLAN', 'TCG_PURCHASEPLANCANCEL', 'TCG_PAYMENT', 'TCG_PURCHASEORDER','TP_AMAZONSHOP'].includes(moduleTable)) {
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (objpage) {
                    objpage = JSON.parse(objpage)
                    res.data.map((v, i) => {
                        objpage.map((n, m) => {
                            if (v.guid == n.guid) {
                                v.LAY_CHECKED = true
                            }
                        })
                    })
                }
            }
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": decimalToFixed(res.data, gridColumns.decimalObj) //表格数据数值类型重赋值
            }
        }
        ,
        done: function (res, curr, count) {
            pagenum = curr
            var ltv = this.elem.next('.layui-table-view');//当前table的dom
            res.data.length || count || ltv.find('.layui-table-header').css('display', 'inline-block');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
            res.data.length || count || ltv.find('.layui-table-box').css('overflow-x', 'auto');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
            if (!['TP_FBALOGISTICSPAYMENT','TP_FBALOGISTICSRECONCILE','TP_FBABOX', 'TP_FBAPLANORDER', 'TCG_PURCHASEPLAN', 'TCG_PURCHASEPLANCANCEL', 'TCG_PAYMENT', 'TCG_PURCHASEORDER'].includes(moduleTable)) {
                if (moduleTable == 'TCG_DISTRIBUTION') data1688 = res.data
                res.data.length || count || ltv.find('.layui-table-body').css('height', ltv.find('.layui-table-body').height() - 17);//数量为0时，表格高度减少滚动条高度
            } else {
                if ($('.spxx').is(':hidden')) {
                    $('.layui-table-body').eq(0).css('height', "75vh");
                } else {
                    $('.layui-table-body').eq(0).css('height', "40vh");
                }
            }
            if (moduleTable == 'TCG_PURCHASEORDER') {
                if (!isbtn) {
                    $('.ishide').hide()
                    $('.isshow').show()
                } else {
                    $('.ishide').show()
                    $('.isshow').hide()
                }
            }

            isdata = false
            fixTotal(this);//修复合计行固定列问题
            rowheight(res, curr);//修复合计行固定列问题
            firstimg()//图片放大

            if (typeof listTableDone == 'function') listTableDone();//如果查询列表存在表格加载完成回调事件，则执行
            document.getElementsByClassName('layui-table-main')[0].scrollTo(scroll.X, scroll.Y);
            scroll = {X: '', Y: ''};
        }
    });


    //单击选中行
    var comguid = ""
    var comobj = ""
    table.on('row(ftable)', function (obj) {
        comobj = obj
        comguid = obj.data.guid
        if (!['TP_FBALOGISTICSPAYMENT','TP_FBALOGISTICSRECONCILE','TP_FBABOX', 'TP_FBAPLANORDER', 'TCG_PURCHASEPLAN', 'TCG_PURCHASEPLANCANCEL', 'TCG_PAYMENT', 'TCG_PURCHASEORDER'].includes(moduleTable)) {
            if (obj.tr.find('input[lay-type="layTableRadio"]').length) {//勾选行单选按钮，重置其他行勾选
                obj.tr.find('input[lay-type="layTableRadio"]').prop("checked", true);//默认无法取消勾选
                layui.each(table.cache.dhtable, function (i, item) {
                    if (obj.tr.data('index') === i) item.LAY_CHECKED = true;
                    else delete item.LAY_CHECKED;
                });
            }
            if (obj.tr.find('input[name="layTableCheckbox"]').length) {//勾选行复选按钮
                layui.each(table.cache.dhtable, function (i, item) {
                    if (obj.tr.data('index') === i) {
                        if (item.LAY_CHECKED) delete item.LAY_CHECKED;//当前行勾选则去除勾选属性
                        else {//当前行未勾选则勾选，并添加属性
                            item.LAY_CHECKED = true;
                            obj.tr.find('input[name="layTableCheckbox"]').prop("checked", true);
                        }
                    }
                });
            }
        } else {
            console.log(obj.data);
            pddata(comobj)
        }
        // form.render();
    });


    window.pddata=function (obj) {
        var updata = ""  
        $('.demo2 .layui-tab-title li').removeClass('layui-this')
        $('.layui-tab-title li').attr('style', 'background:#fff;color:#666666');
        $('.demo2 .layui-tab-title li').eq(0).addClass('layui-this')
        if (['TCG_PAYMENT'].includes(moduleTable)) {
            updata = {'orderID': "'" + obj.data.orderID + "'"}
        } else if (['TCG_DISTRIBUTION'].includes(moduleTable)) {
            updata = {'goodsID': obj.data.goodsID}
        } else {
            updata = {'fBm': obj.data.spBm, 'fNid': obj.data.nid, 'code': obj.data.code}
        }
        $.get('/api/inter/sysMenu/search', updata, function (res) {
            var datalist = res.data.sonList
            var colslist = res.data.gridColumns.gridBody
            if (['TCG_DISTRIBUTION'].includes(moduleTable)) {
                zjgridColumns = res.data.gridColumns
                // zjdata=res.data.sonList
            }

            $.tablelist.init({
                elem: '#pdhtable'
                // ,url: prefix+'/sonlist?pGuid='+obj.data.guid
                , data: datalist
                , limit: 99999
                , totalRow: false
                , cols: [colslist]
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , page: false
                // ,height:moduleTable==''?'full-46':''
                , parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.count, //解析数据长度
                        "data": decimalToFixed(res.data, gridColumns.decimalObj) //表格数据数值类型重赋值
                    }
                }
                , done: function (res, curr, count) {
                    var ltv = this.elem.next('.layui-table-view');//当前table的dom
                    res.data.length || count || ltv.find('.layui-table-header').css('display', 'inline-block');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
                    res.data.length || count || ltv.find('.layui-table-box').css('overflow-x', 'auto');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
                    res.data.length || count || ltv.find('.layui-table-body').css('height', ltv.find('.layui-table-body').height() - 17);//数量为0时，表格高度减少滚动条高度
                    $('.spxx').show()
                    console.log($('.layui-table-body'))
                    $('.layui-table-body.layui-table-main').eq(0).css('height', "35vh");
                    $('.layui-table-body.layui-table-main').eq(1).css('height', "30vh");
                    $('.layui-table-body').eq(1).css('height', "calc(35vh - 15px)");
                    if(['TCG_PURCHASEORDER'].includes(moduleTable))$('.layui-table-body').eq(2).css('height', "calc(35vh - 15px)");
                    fixTotal(this);//修复合计行固定列问题
                    if (typeof listTableDone == 'function') listTableDone();//如果查询列表存在表格加载完成回调事件，则执行
                }
                , jump: function (obj, first) {
                }
            })
        })
    }

    table.on('checkbox(ftable)', function (obj) {
        var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
        if (obj.type == 'all') {//判断是否全选
            var objdata = table.checkStatus('dhtable')
            objdata = objdata.data
            if (obj.checked) {//判断是否选中
                if (objpage) {
                    objpage = JSON.parse(objpage)
                    objpage = objpage.concat(objdata)
                    objpage = newData(objpage)
                } else {
                    objpage = objdata
                }
            } else {
                var objpage = JSON.parse(objpage)
                var deldata = table.cache.dhtable
                objpage = delData(objpage, deldata)
            }
            sessionStorage.setItem(moduleTable + 'checkdata', JSON.stringify(objpage))

        } else {//点击复选框
            if (objpage) {
                objpage = JSON.parse(objpage)
                if (obj.checked) {
                    objpage.push(obj.data)
                } else {
                    objpage.map((v, i) => {
                        if (v.guid == obj.data.guid) {
                            objpage.splice(i, 1)
                        }
                    })
                }
            } else {
                objpage = []
                objpage.push(obj.data)
            }
            if (objpage.length == 0) {
                sessionStorage.removeItem(moduleTable + 'checkdata');
            } else {
                sessionStorage.setItem(moduleTable + 'checkdata', JSON.stringify(objpage))
            }

        }
    });


    element.on('tab(demo1)', function (elem) {
        sessionStorage.removeItem(moduleTable + 'checkdata');
        if (elem.index == 1) {
            tableUrl = tableUrl.replace(/待审核/g, '已审核')
        } else {
            tableUrl = tableUrl.replace(/已审核/g, '待审核')
        }
        table.reload('dhtable', {url: tableUrl});
        if (!$('.spxx').is(':hidden')) {
            $('.spxx').hide()
            $('.layui-table-body').eq(0).css('height', "80vh");
        }
        if (elem.index == 1) {
            isbtn = false
            $('.ishide').hide()
            $('.isshow').show()
            if(moduleTable=='TCG_PURCHASEORDER')$('.layui-table-fixed-r').show()
        } else {
            isbtn = true
            $('.ishide').show()
            $('.isshow').hide()
            if(moduleTable=='TCG_PURCHASEORDER')$('.layui-table-fixed-r').hide()
        }
    });

    element.on('tab(demo2)', function (elem) {
        console.log(elem.elem.context.innerText)
        var bttext = elem.elem.context.innerText
        $("#sontable").empty();
        $("#sontable").append('<table class="layui-hide" id="pdhtable" lay-filter="pftable"></table>');
        if (bttext == '商品信息') {
            if (['TCG_DISTRIBUTION'].includes(moduleTable)) {
                $('.zjbcbtn').show()
            }
            pddata(comobj)
        } else if (bttext == '操作日志') {
            if (['TCG_DISTRIBUTION'].includes(moduleTable)) {
                $('.zjbcbtn').hide()
            }
            oplog(comguid)
        } else if (bttext == '物流信息') {
            $.get(ali1688EcpApiUrl + '/api/1688/get1688OrderTraceInfo', {
                'orderNo': comobj.data.bid,
                'userId': session.userId
            }, function (res) {

                // table.reload('pdhtable', {data:res.data.list,cols:[res.data.gridColumns.gridBody]});
            });
        }
    });

    //双击行事件：查看单据
    table.on('rowDouble(ftable)', function (obj) {
        if (['TCG_PURCHASEORDER'].includes(moduleTable)) return;
        // 部分查询列表无需打开单据页面——精简客户列表、库存查询、edi(特价申请记录、返点发送记录、返点反馈记录、订单发送记录、订单反馈记录)、员工档案（教育经历、工作经历、通讯录）、统计页面（销售业绩、项目利润统计、供应商应付、客户应收、项目应收统计、银行账户余额、银行日记账）、跟踪页面（客户、供应商）、车辆补贴汇总表、型号条码库
        // if(business && $.inArray(business,['customerinfosimple','on','progspecialorderrecord','specialrebatesendrecord','specialrebatereturnrecord','orderprocessspecial','orderprocessspecialreturn','personneldajyjl','personneldagzjl','userbook','usersalesperformance','usersalesperformancexm','providerpayment','clientgathering','clientgatheringxm','bankmoney','bankmoneydetail','customer','provider','orderaccount','carsubsidylist','productgnumber']) == -1){
        switch (moduleTable) {
            case 'THR_PERSONNELDAXX'://hr——档案信息
                parent.layui.index.openTabsPage(openRowUrl + obj.data.nid, businessName + '(' + obj.data.userName + ')');//档案信息查询页面打开详细页面以userName为条件
                break;
            case 'THR_TRAININGPLANENTRYFORMDETAIL'://hr——培训报名表
                $.modal.openSimple('培训报名表' + '-' + obj.data.cUserName + '(' + obj.data.cUser + ')', '/hr/trainingplanentryformdetail/detail?guid=' + obj.data.guid, $(window).width() - 400, $(window).height() - 200);
                break;
            case 'VEDI_STOCKBARGAININSPECIALDETAIL'://edi——特价清单
                layer.open({
                    type: 2,
                    area: ['870px', '680px'],
                    fix: false,//不固定
                    offset: '10%',//距离顶部
                    maxmin: true,//最大最小化
                    shade: 0.3,//遮罩
                    title: '特价清单开票客户详情',
                    content: prefix + '/gcname?tJBID=' + obj.data.tJBID,
                    shadeClose: true,//弹层外区域关闭
                });
                break;
            case 'TP_STOCKPROJECTADDEDTAIL'://查询统计——项目跟踪
                parent.layui.index.openTabsPage(openRowUrl + obj.data.nid, '项目报备(' + obj.data.bid + ')');
                break;
            case 'TP_STOCKBARGAININTAIL'://查询统计——销售合同跟踪
                parent.layui.index.openTabsPage(openRowUrl + obj.data.nid, '销售合同(' + obj.data.bid + ')');
                break;
            case 'TP_STOCKORDERPROCESSTAIL'://查询统计——采购合同跟踪
                parent.layui.index.openTabsPage(openRowUrl + obj.data.nid, '采购合同(' + obj.data.bid + ')');
                break;
            case 'TP_AMAZONSHOP'://查询统计——采购合同跟踪
                parent.layui.index.openTabsPage(openRowUrl + obj.data.guid, '网店资料绑定(' + obj.data.guid + ')');
                break;
            case 'THR_VPSMANAGE'://查询统计——采购合同跟踪
                parent.layui.index.openTabsPage(openRowUrl + obj.data.guid, 'VPS管理(' + obj.data.guid + ')');
                break;
            default://普通打开单据页面
                if (typeof buttonState == 'object' && buttonState['list-add'] !== 'hidden') parent.layui.index.openTabsPage(openRowUrl + obj.data.nid, businessName + '(' + obj.data.bid + ')');
                break;
        }
        // }
    });
    //头工具栏事件
    table.on('toolbar(ftable)', function (obj) {
        var checkStatus = table.checkStatus('dhtable');
        switch (obj.event) {
            case 'addbtn'://新增
                parent.layui.index.openTabsPage(openRowUrl.split('?')[0], businessName + ' - 新增');
                break;
            case 'importBtn'://导入
                if (importFields) {
                    thStr = '<tr><th><div style="width:30px;">序号</div></th>';
                    $.each(importFields, function (i, val) {
                        fieldWidth[val] = fieldWidth[val] ? fieldWidth[val] : 100;			//默认宽度100px
                        thStr += '<th><div style="width:' + fieldWidth[val] + 'px;">' + i + '</div></th>';
                    })
                    thStr += '</tr>';
                    layer.open({
                        type: 1,
                        area: ['400px', '230px'],
                        fix: false,
                        offset: '10%',
                        maxmin: true,
                        shade: 0.3,
                        title: importTitle,
                        content: $('#importTpl').html(),
                        btn: ['<i class="dhicon dh-check"></i> 导入', '<i class="dhicon dh-remove"></i> 取消'],
                        shadeClose: true,
                        zIndex: 1000,
                        btn1: function (index, layero) {
                            var file = layero.find('#file');
                            if (!file[0]['value']) {
                                layer.msg("请选择文件！");
                                return false;
                            }
                            var imRes = importListExcel(file[0], importFields, business);
                        }
                    });
                } else {
                    $.modal.alertWarning("后台未返回导入模板对象！");
                }
                break;
            case 'exportbtn'://导出
                $.ajax({
                    url: exportUrl,
                    type: 'GET',
                    data: getWherestr(),
                    dataType: 'json',
                    beforeSend: function () {
                        showloadings(true);
                    },
                    success: function (result) {
                        if (result.code == 0) {
                            window.location.href = ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true;
                            parent.$('.page-loading').hide();//页面进行了跳转刷新，需要手动关闭页面的加载动画
                        } else if (result.code == web_status.WARNING) {
                            $.modal.alertWarning(result.msg)
                        } else {
                            $.modal.alertError(result.msg);
                        }
                        showloadings(false);
                    }
                });
                break;
            case 'deleteBatch'://删除
                if (!['TCG_PURCHASEORDER','TP_AMAZONSHOP'].includes(moduleTable)) {
                    if (checkStatus.data.length == 0) {
                        layer.msg("请先选择数据！");
                    } else {
                        console.log("2")
                        $.modal.confirmCom('确定要删除么？', function (result) {
                            var infoItems = [];
                            $.each(checkStatus.data, function (i, v) {
                                if (business == 'personneldaxx') {
                                    infoItems[i] = {nid: v.nid};
                                } else {
                                    infoItems[i] = {guid: v.guid};
                                }
                            })
                            $.operate.post(delUrl, {infoItems: JSON.stringify(infoItems)}, function (result) {
                                setTimeout(function () {
                                    table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                                }, 1000);
                            });
                        });
                    }
                } else {
                    var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                    if (!objpage) {
                        layer.msg("请先选择数据！");
                    } else {
                        let msg = "确定要删除么？";
                        if (moduleTable === "TCG_PURCHASEORDER"){
                            msg = "该操作将删除所有关联的采购计划单!";
                        }
                        $.modal.confirmCom(msg, function (result) {
                            var infoItems = JSON.parse(objpage)
                            $.operate.post(delUrl, {infoItems: JSON.stringify(infoItems)}, function (result) {
                                setTimeout(function () {
                                    table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                                }, 1000);
                            });
                        });
                    }
                }

                break;
            case 'shbtn'://采购订单审核
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (!objpage) {
                    layer.msg("请先选择数据！");
                } else {
                    $.modal.confirmCom('是否确认审核？(需先创建订单)', function (result) {
                        var infoItems = JSON.parse(objpage)
                        var dataAll = []
                        $.each(infoItems, function (i, v) {
                            dataAll.push({'guid': v.guid, 'state': '已审核'})
                        })
                        $.operate.post(prefix + '/updateType', {infoItems: JSON.stringify(dataAll)}, function (result) {
                            setTimeout(function () {
                                sessionStorage.removeItem(moduleTable + 'checkdata');
                                table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                            }, 1000);
                        });
                    });
                }
                break;
            case 'scorderbtn'://采购计划生成订单
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (!objpage) {
                    layer.msg("请先选择数据！");
                } else {
                    $.modal.confirmCom('确定要生成订单么？', function (result) {
                        var infoItems = JSON.parse(objpage)
                        $.operate.post(prefix + '/createOrder', {infoItems: JSON.stringify(infoItems)}, function (result) {
                            setTimeout(function () {
                                sessionStorage.removeItem(moduleTable + 'checkdata');
                                table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                            }, 1000);
                        });
                    });
                }
                break;
            case 'htbtn'://采购订单回退
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (!objpage) {
                    layer.msg("请先选择数据！");
                } else {
                    $.modal.confirmCom('确定要回退么？', function (result) {
                        var infoItems = JSON.parse(objpage)
                        var dataAll = []
                        $.each(infoItems, function (i, v) {
                            dataAll.push({'guid': v.guid, 'state': '待审核'})
                        })
                        $.operate.post(prefix + '/updateType', {infoItems: JSON.stringify(dataAll)}, function (result) {
                            setTimeout(function () {
                                sessionStorage.removeItem(moduleTable + 'checkdata');
                                table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                            }, 1000);
                        });
                    });
                }
                break;
            case 'xsfkbtn'://采购订单线上付款
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (!objpage) {
                    layer.msg("请先选择数据！");
                } else {
                    $.modal.confirmCom('确定要跳转线上付款页么？', function (res) {
                        sessionStorage.setItem('isxsfk',1)
                        parent.layui.index.openTabsPage('purchase/payment/edit?nid=0', '线上付款单-新增');
                        layer.closeAll()
                    });
                }
                break;
            case 'qxbtn'://采购订单 取消订单
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (!objpage) {
                    layer.msg("请先选择数据！");
                } else {
                    layer.prompt({title: '请输入取消原因', formType: 2}, function (cancelReason, index) {
                        var infoItems = JSON.parse(objpage)
                        var orderID = ""
                        $.each(infoItems, function (i, v) {
                            orderID += (v.bid + ",")
                        })
                        orderID = orderID.substring(0, orderID.length - 1)
                        var index1 = layer.load();
                        $.post(ali1688EcpApiUrl + '/api/1688/cancel1688Order', {
                            'orderNos': orderID,
                            userId: session.userId,
                            cancelReason:cancelReason
                        }, function (result) {
                            setTimeout(function () {
                                sessionStorage.removeItem(moduleTable + 'checkdata');
                                table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                            }, 1000);
                            if (result.success === true) {
                                layer.alert(result.message, {icon: 1});
                            } else {
                                layer.alert(result.message, {icon: 2});
                            }
                            layer.close(index1);//取消等待
                        });
                    });
                    // $.modal.confirmCom('确定要取消么？',function(result){
                    // 	var infoItems=JSON.parse(objpage)
                    // 	var orderID = ""
                    // 	$.each(infoItems,function(i,v){
                    // 		orderID+=(v.bid+",")
                    // 	})
                    // 	orderID = orderID.substring(0,orderID.length-1)
                    // 	var index = layer.load();
                    // 	$.post(ali1688EcpApiUrl+'/api/1688/cancel1688Order',{'orderNos':orderID,userId:session.userId},function(result){
                    // 		setTimeout(function(){
                    // 			sessionStorage.removeItem(moduleTable+'checkdata');
                    // 			table.reload('dhtable', {page: {curr: 1},where:getWherestr()});
                    // 		}, 1000);
                    // 		if (result.success === true){
                    // 			layer.alert(result.message,{icon : 1});
                    // 		}else{
                    // 			layer.alert(result.message,{icon : 2});
                    // 		}
                    // 		layer.close(index);//取消等待
                    //
                    // 	});
                    // });
                }
                break;
            case 'scbtn'://采购订单 创建订单
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (!objpage) {
                    layer.msg("请先选择数据！");
                } else {
                    // $.open()
                    $.modal.confirmCom('确定要重新创建订单么？', function (result) {
                        var infoItems = JSON.parse(objpage)
                        var orderID = ""
                        $.each(infoItems, function (i, v) {
                            orderID += (v.bid + ",")
                        })
                        orderID = orderID.substring(0, orderID.length - 1)
                        var index = layer.load();
                        $.post(ali1688EcpApiUrl + '/api/1688/create1688Order', {
                            'orderNos': orderID,
                            userId: session.userId
                        }, function (result) {
                            setTimeout(function () {
                                sessionStorage.removeItem(moduleTable + 'checkdata');
                                table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                            }, 1000);
                            if (result.success === true) {
                                layer.alert(result.message, {icon: 1});
                            } else {
                                layer.alert(result.message, {icon: 2});
                            }
                            layer.close(index);//取消等待
                        });
                    });
                }
                break;
            case 'zfbth'://采购付款 线上支付
                var objpage = sessionStorage.getItem(moduleTable + 'checkdata')
                if (!objpage) {
                    layer.msg("请先选择数据！");
                } else {
                    $.modal.confirmCom('确定要跳转支付么？', function (result) {
                        var infoItems = JSON.parse(objpage)
                        var orderID = ""
                        $.each(infoItems, function (i, v) {
                            orderID += (v.orderNumber !== "" && v.orderNumber !== null ? v.orderNumber + "," : "")
                        })
                        orderID = orderID.substring(0, orderID.length - 1)
                        if (orderID === "") return layer.msg("订单ID不可为空！");
                        var index = layer.load();
                        $.post(ali1688EcpApiUrl + '/api/1688/get1688AlipayUrl', {
                            'aliOrderNos': orderID,
                            userId: session.userId
                        }, function (result) {
                            if (result.success == true) {
                                setTimeout(function () {
                                    sessionStorage.removeItem(moduleTable + 'checkdata');
                                    table.reload('dhtable', {page: {curr: 1}, where: getWherestr()});
                                }, 1000);
                                window.open(result.extendAttr);
                                layer.closeAll();
                                // layer.open({
                                // 	type: 2,
                                // 	area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
                                // 	fix: false,//不固定
                                // 	offset: '10%',//距离顶部
                                // 	maxmin: true,//最大最小化
                                // 	shade: 0.3,//遮罩
                                // 	title: '支付',
                                // 	content: result.extendAttr,
                                // 	btn: ['取消'],
                                // 	shadeClose: true,// 弹层外区域关闭
                                // });
                            } else {
                                layer.alert(result.message, {icon: 2});

                            }
                            layer.close(index);//取消等待
                        });
                    });
                }
                break;
            case 'fieldSet'://列设置
                filedSet(moduleTable);
                break;
            case 'group'://整单切换
                if (business.split('/')[business.split('/').length - 1] == 'group') window.location.href = prefix.substring(0, prefix.lastIndexOf('/') + 1);
                else window.location.href = prefix + '/listgrouppage';
                break;
            case 'tail'://跟踪查询
                if (checkStatus.data.length == 0) {
                    layer.msg("请先选择数据！");
                } else {
                    switch (business) {
                        case 'customer':
                            parent.layui.index.openTabsPage("/crm/customer/tail?gClient=" + checkStatus.data[0].gClient, '客户信息(' + checkStatus.data[0].gClient + ') - 跟踪');
                            break;
                        case 'provider':
                            parent.layui.index.openTabsPage("/crm/provider/tail?gprovide=" + checkStatus.data[0].gprovide, '供应商信息(' + checkStatus.data[0].gprovide + ') - 跟踪');
                            break;
                        default:
                            parent.layui.index.openTabsPage("/business/" + (business.split('/')[1] ? business.split('/')[0] : business) + "/tail?bid=" + checkStatus.data[0].bid, businessName + '(' + checkStatus.data[0].bid + ') - 跟踪');
                            break;
                    }
                }
                break;
            case 'take'://组装拆卸——出入库
                if (moduleTable == 'TP_STOCKTAKEDOWN' || moduleTable == 'TP_STOCKTAKEDOWNGROUP') window.location.href = '/business/take/takeon';
                if (moduleTable == 'TP_STOCKTAKEON' || moduleTable == 'TP_STOCKTAKEONGROUP') window.location.href = "/business/take";
                break;
            case 'calendar'://计划日程
                var myDate = new Date();
                //获取当前年
                var year = myDate.getFullYear();
                //获取当前月
                var month = myDate.getMonth() + 1;
                month = month < 10 ? '0' + month : month;
                if (moduleTable == 'TCRM_WEEKLYPLAN') window.location.href = "/crm/" + business + '/weeklyCalendar?dPlanDate=' + year + '-' + month;
                if (moduleTable == 'TOA_MEETINGROOMAPPOINTMENT') window.location.href = '/oa/meetingroomappointment/calendar?dKsSj=' + year + '-' + month;
                if (moduleTable == 'PROQR_PERSONSCHEDULING') window.location.href = '/crm/scheduling/calendar?dXcDate=' + year + '-' + month;
                break;
            case 'workdate'://一键生成打卡时间
                layer.open({
                    type: 1,
                    offset: '20%',
                    title: '一键生成打卡时间',
                    shade: 0.3,//遮罩
                    shadeClose: true,// 弹层外区域关闭
                    area: ['300px', '200px'],
                    content: $('#selectYear').html(),
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        if (layero.find('#vYear').val()) {
                            $.modal.confirmCom('系统将按默认规则生成' + layero.find('#vYear').val() + '年工作（打卡）时间，若已有相关记录，将会被更新覆盖，是否确认生成？', function (result) {
                                $.operate.post('/hr/attendanceworkdateset/insertworkdate', {'vYear': layero.find('#vYear').val()}, function (result) {
                                    setTimeout(function () {
                                        layer.close(index);
                                        table.reload('dhtable');
                                    }, 1000);
                                });
                            });
                        } else {
                            layer.msg("请选择一键生成打卡时间的年份！", {icon: 7});
                        }
                    }
                });
                break;
        }
        ;
    });

    //监听工具条
    table.on('tool(ftable)', function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'workday'://工作时间设定——工作日
                var pd = [];
                pd.push(data);
                $.operate.post('/hr/attendanceworkdateset/editworkday', {'attendanceWorkDateSetItems': JSON.stringify(pd)}, function (res) {
                    if (res.code == 0) table.reload('dhtable');
                });
                break;
            case 'holiday'://工作时间设定——休息日
                var pd = [];
                pd.push(data);
                $.operate.post('/hr/attendanceworkdateset/editholiday', {'attendanceWorkDateSetItems': JSON.stringify(pd)}, function (res) {
                    if (res.code == 0) table.reload('dhtable');
                });
                break;
            case 'editDay'://工作时间设定——修改
                $.modal.open('工作时间修改——' + data.dWorkDate, '/hr/attendanceworkdateset/edit?guid=' + data.guid, 680, 580, function (index) {
                    var res = window["layui-layer-iframe" + index].callbackdata();
                    if (typeof res == 'string') {
                        layer.msg(res, {icon: 7});
                    } else {
                        $.operate.post('/hr/attendanceworkdateset/editpost', {'attendanceWorkDateSetItems': JSON.stringify(res)}, function (res) {
                            if (res.code == 0) {
                                layer.close(index);
                                table.reload('dhtable');
                            }
                        });
                    }
                });
                break;
            case 'viewUserBook':
                if (data.userPicture) {
                    $(".c-photo").attr('src', data.userPicture);
                } else {
                    if (data.userSexDA == '女') {
                        $(".c-photo").attr('src', '../img/profile.jpg');
                    } else if (data.userSexDA == '男') {
                        $(".c-photo").attr('src', '../img/boy.png');
                    } else {
                        $(".c-photo").attr('src', '../img/unknow.png');
                    }
                }
                $(".c-userName").html(data.userName);
                $(".c-deptName").html(data.deptName);
                $(".c-cidName").html(data.cidName);
                $(".c-positionName").html(data.positionName);
                $(".c-userPhone1").html(data.userPhone1);
                $(".c-userEmail").html(data.userMail);
                showpic();
                break;
            case 'modifybz':
                // if (session)
                console.log("session",session.userId,data,userId)
                if(session.userId === data.userId){
                    layer.open({
                        type: 1,
                        area: ['400px', '200px'],
                        offset: '10%',
                        content: `<div><textarea name="desc" placeholder="请输入备注内容" class="layui-textarea bzvalue">${data.vBzXx ? data.vBzXx : ''}</textarea></div>`,
                        btn: ['确认', '取消'],
                        yes: function (index, layero) {
                            var vBzXx = $('.bzvalue').val()
                            $.operate.post('/system/userbook/editpost', {vBzXx, 'userId': data.userId}, function (res) {
                                if (res.code == 0) {
                                    layer.close(index);
                                    table.reload('dhtable');
                                }
                            });
                        }
                    });
                }else{
                    layer.msg("不可修改他人信息！");
                }

                break;
            default:
                break;
        }
    });
    //监听排序事件
    table.on('sort(ftable)', function (obj) {
        $.tablelist.sort('dhtable', obj);
    });
})

function showpic() {
    $("#showpic").show();
    $("#lightbox_mask").show();
    $(".close").click(function () {
        $("#showpic").hide();
        $("#lightbox_mask").hide();
    })
    $("#showpic").click(function () {
        $("#showpic").hide();
        $("#lightbox_mask").hide();
    })
    $("#viewCard").click(function (event) {
        event.stopPropagation();    //  阻止事件冒泡
    });
}

//下载导入模板
function getTemplate() {
    $.tablelist.importTemplate(templateUrl);
}

/*批量请求导入数据
 *tobj：导入数据对象
 *startNum：从第几条开始导入
 *oneImportNum：每次导入条数
 *allImportNum：总数据量
 *times：导入次数
 */
var cID = bUser = bDept = stepName = '';

function eachImport(tobj, startNum, oneImportNum, allImportNum, times, timeNum) {
    var importObj = [],
        inum = startNum,
        importBl = '0%',
        res,
        importUrl = prefix + "/importpost";
    for (var i = startNum; i < startNum + oneImportNum; i++) {
        if (i >= allImportNum) break;
        inum = i + 1;
        importObj.push(tobj[i]);
    }
    if (moduleTable == 'THR_POSITIONINSTRUCTIONS') importUrl = prefix + "/importdatapost";//单独判断，岗位说明书不同的导入接口
    $.ajaxSettings.async = false;
    $.post(importUrl, {'infoItems': JSON.stringify(importObj, null, 2)}, function (result) {
        importBl = (inum / allImportNum) * 100;
        console.log('导入比:' + importBl.toFixed(2) + '%');
        console.log('数量:' + inum);
        console.log('总次数:' + times);
        console.log('当前次数:' + timeNum);
        importObj = [];
        timeNum += 1;
        res = result;
    }, "json");
    setTimeout(function () {
        if (timeNum <= times) {
            eachImport(tobj, startNum + oneImportNum, oneImportNum, allImportNum, times, timeNum);
        } else {
            element.progress('dhprogress', importBl.toFixed(2) + '%');
            showloadings(false);
            closeProcess(res);
        }
        element.progress('dhprogress', importBl.toFixed(2) + '%');
    }, 500);
}

// 筛选1个数组相同的数据
function newData(arr) {
    const map = {};
    arr.forEach(item => {
        const obj = {};
        Object.keys(item).sort().map(key => obj[key] = item[key]);
        map[JSON.stringify(obj)] = item;
    });
    return Object.keys(map).map(key => JSON.parse(key));
}

// 筛选2个数组相同的数据
function delData(data, deldata) {
    data.forEach(item => {
        deldata = deldata.filter(items => items.guid != item.guid);
    });
    return deldata;
}

//滚动条位置
function GetPageScroll() {
    y = document.getElementsByClassName('layui-table-main')[0].scrollTop
    x = document.getElementsByClassName('layui-table-main')[0].scrollLeft
    return {X: x, Y: y};
}